package com.example.vehicleservice.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.vehicleservice.entity.Student;
import com.example.vehicleservice.mapper.StudentMapper;
import com.example.vehicleservice.service.IStudentService;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author cc
 * @since 2022-06-09
 */
@Service
public class StudentServiceImpl extends ServiceImpl<StudentMapper, Student> implements IStudentService {

    @Autowired
    private StudentMapper studentMapper;
    @Autowired
    private RestTemplate restTemplate;

    @GlobalTransactional(name = "vehicle-service", rollbackFor = Exception.class)
    @Override
    public String remove() {
        List<Student> students = studentMapper.getLastData();
        //往后台插入
        HttpHeaders headers = new HttpHeaders();
        MultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
        System.out.println(JSONObject.toJSONString(students));
        //请求参数
        map.add("students", JSONObject.toJSONString(students));
        HttpEntity<MultiValueMap<String, Object>> request = new HttpEntity<>(map, headers);
        ResponseEntity<String> responseEntity = restTemplate.postForEntity("http://localhost:8080/student/add",request, String.class);
        String body = responseEntity.getBody();
        if ("后台新增数据成功".equals(body)) {
            throw new RuntimeException("后台新增数据失败");
        }
        //删减移动数据
        studentMapper.removeLastData();
        return "移除完成";
    }
}
